package licode.unisop.realm.application.service;

import cn.hutool.core.util.StrUtil;
import licode.unisop.provider.api.SiUserProvider;
import licode.unisop.provider.info.SiRealmReg;
import licode.unisop.realm.application.gateway.SiUserProviderManager;
import licode.unisop.realm.client.api.SiRealmProviderQueryService;
import licode.unisop.realm.client.dto.SiRealmProviderDTO;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 初始化用户环境
 *
 * @author licode
 */
@Service
public class UserInit implements ApplicationRunner {
    @Resource
    private SiRestfulCallUtil siRestfulCallUtil;

    @Resource
    private SiUserProvider siUserProvider;

    @Resource
    private SiUserProviderManager siUserProviderManager;

    @Resource
    private SiRealmProviderQueryService siRealmProviderQueryService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<SiRealmProviderDTO> providers = siRealmProviderQueryService.getRealmProviderList();
        if (null != providers) {
            providers.forEach(item -> {
                if (StrUtil.isNotBlank(item.getSource())) {
                    if ("REALM".equals(item.getType()) && "URL".equals(item.getMode())) {
                        siUserProviderManager.registerUserProvider(
                                SiRealmReg.builder()
                                        .providerId(item.getId())
                                        .providerName(item.getName())
                                        .provider(new SiUserProviderUrl(siRestfulCallUtil, item.getSource()))
                                        .build()
                        );
                    }
                }
            });
        }

        siUserProviderManager.registerUserProvider(
                SiRealmReg.builder()
                        .providerId("default")
                        .providerName("默认")
                        .provider(siUserProvider)
                        .build()
        );
    }
}
